<?php

namespace callback;

use QYS\Util\Formater;
use QYS\Protocol\Request;
use QYS\Protocol\Response;
use QYS\Socket\Callback\SwooleProcess;
use QYS\Log\Log;
use QYS\Util\Debug;
use QYS\Db\Redis;
use QYS\Db\Mysql;
use QYS\Db\Mongo;
use QYS\third\Crypto\XXTEA;
use QYS\Core\Config;
use \Yosymfony\Toml\Toml;
use Swoole\Coroutine as co;
use globalunit\utils\Config as Cnf;
use globalunit\utils\QueueHelper;
use QYS\Core\Factory as CFactory;

use globalunit\utils\UniqueMessageQueueWithDelay;

class SwooleRechargeProcess extends SwooleProcess
{
    private $appname;
    private $gamename;
    private $version;
    private $lasttime;
    private $worker;
    private $workerId;

    public function __construct()
    {
    }

    public function onWorkerStart($process, $workerId, $work_num)
    {
        $this->workerId = $workerId;
        $gamename = Config::get("gamename");
        $this->gamename = $gamename;



        $version = Config::get("version");
        $this->version = $version;

        $GLOBALS['GAMENAME'] = $gamename;
        $GLOBALS['VERSION'] = $version;

        $GLOBALS['WORKERID'] = $workerId;
        $GLOBALS['WORKERCOUNT'] = $work_num;

        if ($workerId == 0) {
            $r = Redis::newInstance("queue");
            $this->copyback($r);
        }
    }


    public function copyback($rediscli)
    {
        $LOG_QUEUE_NAME = "$this->gamename:logqueue";
        $LOG_QUEUE_BACKUP_NAME = "$this->gamename:logqueuebackup";
        $LPOPRPUSH = <<<crifan
                    local v = redis.call('lpop', KEYS[1])
                    if not v then
                        return nil
                    end
                    redis.call('rpush', KEYS[2], v)
                    return v
crifan;
        $args_args = array($LOG_QUEUE_BACKUP_NAME, $LOG_QUEUE_NAME);
        $a = $rediscli->eval($LPOPRPUSH, $args_args, 2);
        while ($a != null) {
            $a = $rediscli->eval($LPOPRPUSH, $args_args, 2);
        }
    }

    public function loop()
    {
        $LOG_QUEUE_NAME = "$this->gamename:logqueue";
        $LOG_QUEUE_BACKUP_NAME = "$this->gamename:logqueuebackup";
        $params = array("workerId" => $this->workerId);
        $handler = CFactory::getInstance("handler\\RechargeHandler", $params);
        $r = Redis::newInstance("queue");
        try {
            $res = $r->brpoplpush($LOG_QUEUE_NAME, $LOG_QUEUE_BACKUP_NAME, 10);
            if ($res) {
                $cmd = json_decode($res, true);
                $handler->handle($cmd);
                $r = $r->lrem($LOG_QUEUE_BACKUP_NAME, $res, -1);
                Log::var_dump(['删除结果--->'=> $r]);
            }
        } catch (\Exception $e) {
            var_dump($e->getMessage());
            // break;
        }
        return true;
    }

    public function onWorkerStop($process)
    {
    }
}
